package com.yami.shop.sys.platform.controller;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.response.ResponseEnum;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.platform.model.YamiSysUser;
import com.yami.shop.security.platform.util.SecurityUtils;
import com.yami.shop.sys.common.constant.MenuType;
import com.yami.shop.sys.common.model.ShopMenu;
import com.yami.shop.sys.common.service.ShopMenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Set;


/**
 * 菜单管理
 *
 * @author yami
 * @date 2021-03-01 17:42:09
 */
@Tag(name = "菜单管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/sys/shopMenu")
public class ShopMenuController {

    private final ShopMenuService shopMenuService;

    @Value("${yami.expose.operation.auth:}")
    private Boolean permission;

    @GetMapping("/page")
    @Operation(summary =  "分页查询", description = "分页查询")
    public ServerResponseEntity<IPage<ShopMenu>> getShopMenuPage(PageParam<ShopMenu> page,@ParameterObject ShopMenu shopMenu) {
        return ServerResponseEntity.success(shopMenuService.page(page, new LambdaQueryWrapper<ShopMenu>()));
    }

    @GetMapping("/table")
    @Operation(summary =  "获取菜单页面的表", description = "获取菜单页面的表")
    public ServerResponseEntity<List<ShopMenu>> table() {
        YamiSysUser sysUser = SecurityUtils.getSysUser();
        List<ShopMenu> shopMenus = shopMenuService.listMenuAndBtn(sysUser.getUserId());
        return ServerResponseEntity.success(shopMenus);
    }

    /**
     * 所有菜单列表(用于新建、修改角色时 获取菜单的信息)
     */
    @GetMapping("/list")
    @Operation(summary =  "获取用户所拥有的菜单(不包括按钮)", description = "通过登陆用户的userId获取用户所拥有的菜单和权限")
    public ServerResponseEntity<List<ShopMenu>> list() {
        List<ShopMenu> shopMenus = shopMenuService.listSimpleMenuNoButton();
        return ServerResponseEntity.success(shopMenus);
    }

    @GetMapping("/listRootMenu")
    @Operation(summary =  "获取菜单列表", description = "获取菜单列表")
    public ServerResponseEntity<List<ShopMenu>> listRootMenu() {
        //查询列表数据
        List<ShopMenu> shopMenus = shopMenuService.listRootMenu();
        return ServerResponseEntity.success(shopMenus);
    }

    @GetMapping("/listChildrenMenu")
    @Operation(summary =  "获取子菜单列表", description = "获取子菜单列表")
    @Parameter(name = "parentId", description = "上级菜单id")
    public ServerResponseEntity<List<ShopMenu>> listChildrenMenu(Long parentId) {
        //查询列表数据
        List<ShopMenu> shopMenus = shopMenuService.listChildrenMenuByParentId(parentId);
        return ServerResponseEntity.success(shopMenus);
    }

    @GetMapping("/info/{menuId}")
    @Operation(summary =  "查询菜单管理", description = "通过id查询菜单管理")
    @Parameter(name = "menuId", description = "菜单id")
    public ServerResponseEntity<ShopMenu> getById(@PathVariable("menuId") Long menuId) {
        ShopMenu shopMenu = shopMenuService.getShopMenu(menuId);
        return ServerResponseEntity.success(shopMenu);
    }

    @PostMapping
    @Operation(summary =  "新增菜单信息", description = "新增菜单信息")
    public ServerResponseEntity<Void> save(@RequestBody @Valid ShopMenu shopMenu) {
        if (BooleanUtil.isFalse(permission)) {
            return ServerResponseEntity.fail(ResponseEnum.NOT_FOUND);
        }
        shopMenuService.saveShopMenu(shopMenu);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary =  "修改菜单信息", description = "修改菜单信息")
    public ServerResponseEntity<Void> updateById(@RequestBody @Valid ShopMenu shopMenu) {
        if (BooleanUtil.isFalse(permission)) {
            return ServerResponseEntity.fail(ResponseEnum.NOT_FOUND);
        }
        if (shopMenu.getType() == MenuType.MENU.getValue() && StrUtil.isBlank(shopMenu.getUrl())) {
            // 菜单URL不能为空
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.sys.menu.exist"));
        }
        shopMenuService.updateShopMenu(shopMenu);
        //修改子菜单按钮显示隐藏状态
        Set<String> perms = shopMenuService.updateSonMenuState(shopMenu.getMenuId(), shopMenu.getHidden());
        //获取用户的所有菜单权限信息
        Set<String> authorities = SecurityUtils.getSysUser().getAuthorities();
        //隐藏就移除用户对应按钮的权限信息，显示就添加
        if (shopMenu.getHidden() == 1){
            //移除
            authorities.removeAll(perms);
        }else {
            //添加
            authorities.addAll(perms);
        }
        return ServerResponseEntity.success();
    }

    @DeleteMapping("/{menuId}")
    @Operation(summary =  "删除菜单管理", description = "通过id删除菜单管理")
    @Parameter(name = "menuId", description = "菜单id")
    public ServerResponseEntity<String> removeById(@PathVariable Long menuId) {
        if (BooleanUtil.isFalse(permission)) {
            return ServerResponseEntity.fail(ResponseEnum.NOT_FOUND);
        }
        if(menuId <= Constant.SYS_MENU_MAX_ID){
            // 系统菜单，不能删除
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.sys.menu.delete.error"));
        }
        //判断是否有子菜单或按钮
        List<ShopMenu> shopMenus = shopMenuService.listChildrenMenuByParentId(menuId);
        if(shopMenus.size() > 0){
            // 请先删除子菜单或按钮
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.sys.menu.child.delete"));
        }

        shopMenuService.deleteMenuAndRoleMenu(menuId);
        return ServerResponseEntity.success();
    }
}
